package connection;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import midlet.MobileUCMIDlet;
import util.MobileCache;
import util.ReadXML;

/**
 *
 * @author psychok7
 */
public class Connection {

    private String authenticationUrl = "http://localhost:8080/MobileUC_Server/servlet/Servlets.AuthenticationServlet";
    private String requestURL = "http://localhost:8080/MobileUC_Server/servlet/Servlets.Mobile_ucServlet";
    private HttpConnection httpConn = null;
    private Timer timer = new Timer();
    private TestTimerTask task = new TestTimerTask(null);
    private String username;
    private String downloadinfo;
    private String oldXML = "";
    public boolean flag_updatedserver = false;
    private MobileUCMIDlet midlet;

    public Connection(String username, MobileUCMIDlet midlet) {
        this.username = username;
        this.midlet = midlet;
    }

    public class TestTimerTask extends TimerTask {

        public String username;

        public TestTimerTask(String username) {
            this.username = username;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public final void run() {
            System.out.println("update from server " + this.username);
            getXmlFromServer(requestURL, "request_source=mobile&username=" + this.username);
            if (flag_updatedserver == true) {
                midlet.newAlert = true;
            }

        }
    }

    public int getXmlFromServer(String url, String params) {
        try {
            httpConn = (HttpConnection) Connector.open(url);
            httpConn.setRequestMethod(HttpConnection.POST);

            httpConn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Confirguration/CLDC-1.0");
            httpConn.setRequestProperty("Content-Language", "en-CA");
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            byte[] data = params.getBytes();

            httpConn.setRequestProperty("Content-Length", Integer.toString(data.length));

            //request parameters
            OutputStream out = httpConn.openOutputStream();
            out.write(data);
            out.close();

            //get HTTP code
            int statusCode = httpConn.getResponseCode();
            if (statusCode == HttpConnection.HTTP_OK) {
                StringBuffer sb = new StringBuffer();
                InputStream is = httpConn.openDataInputStream();
                int chr;
                while ((chr = is.read()) != -1) {
                    sb.append((char) chr);
                }
                downloadinfo = sb.toString();

                if (!(this.oldXML.equals(downloadinfo))) {
                    this.flag_updatedserver = true;
                    this.oldXML = downloadinfo;
                } else {
                    this.flag_updatedserver = false;
                }

                ReadXML read = new ReadXML(new MobileCache().saveMobileCache(sb.toString(), this.username), "getAll", null);
                read.start();
                try {
                    read.join();
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
                is.close();
            }

            httpConn.close();
            return statusCode;
        }//try
        catch (IOException ex) {
            return 0;
        }//catch
    }

    public String downloadMaterialdeApoio(String choice) {

        getXmlFromServer(requestURL, "request_source=mobile&username=" + choice);
        ReadXML read = new ReadXML(downloadinfo, "getMaterial", null);
        read.start();
        try {
            read.join();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        return read.getInfo();

    }

    public String processRequest(String mode, String type) {
        MobileCache cache = new MobileCache();
        oldXML = cache.loadMobileCache(this.username);
        ReadXML read = new ReadXML(oldXML, mode, type);
        read.start();
        try {
            read.join();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        return read.getInfo();
    }

    public boolean checkUserCredentials(String username, String password) {
        int statusCode = httpPostRequest(authenticationUrl, "request_source=mobile&username=" + username + "&password=" + password);


        if (statusCode == HttpConnection.HTTP_OK) {
            getXmlFromServer(requestURL, "request_source=mobile&username=" + username);
            this.task.setUsername(username);
            timer.scheduleAtFixedRate(this.task, 1000 * 30, 1000 * 30);
            return true;
        } else if (statusCode == HttpConnection.HTTP_INTERNAL_ERROR) {
            System.out.println("internal error");
        }//else if
        else if (statusCode == HttpConnection.HTTP_BAD_REQUEST) {
            System.out.println("bad request");
        }//else if
        else if (statusCode == HttpConnection.HTTP_FORBIDDEN) {
            System.out.println("http forbidden");
        }//else if
        else if (statusCode == HttpConnection.HTTP_NOT_IMPLEMENTED) {
            System.out.println("not_implemented");
        }//else if
        else if (statusCode == HttpConnection.HTTP_UNAUTHORIZED) {
            System.out.println("unauthorized");
        }//else if
        else {
            System.out.println("generic error");
        }//else

        new ReadXML(new MobileCache().loadMobileCache(this.username), "getAll", null).start();
        return false;
    }//checkUserCredentials

    private int httpPostRequest(String url, String params) {
        try {
            httpConn = (HttpConnection) Connector.open(url);
            httpConn.setRequestMethod(HttpConnection.POST);

            httpConn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Confirguration/CLDC-1.0");
            httpConn.setRequestProperty("Content-Language", "en-CA");
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");


            byte[] data = params.getBytes();

            httpConn.setRequestProperty("Content-Length", Integer.toString(data.length));

            //request parameters
            OutputStream out = httpConn.openOutputStream();
            out.write(data);
            out.close();

            //get HTTP code
            int statusCode = httpConn.getResponseCode();
            if (statusCode == HttpConnection.HTTP_OK) {
                StringBuffer sb = new StringBuffer();
                InputStream is = httpConn.openDataInputStream();
                int chr;
                while ((chr = is.read()) != -1) {
                    sb.append((char) chr);
                }

                is.close();
            }

            httpConn.close();
            return statusCode;
        }//try
        catch (IOException ex) {
            return 0;
        }//catch
    }//httpPostRequest

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public boolean isFlag_updatedserver() {
        return flag_updatedserver;
    }

    public void setFlag_updatedserver(boolean flag_updatedserver) {
        this.flag_updatedserver = flag_updatedserver;
    }

    public String getAuthenticationUrl() {
        return authenticationUrl;
    }
}
